<template>
  <MainContent title="积分管理">
    <template #search-bar>
      <SearchBar inline>
        <template #normal>
          <el-form-item label="积分名称">
            <el-input
              v-model="tableForm.name"
              clearable
              placeholder="请输入积分名称"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="tableForm.status"
              class="m-2"
              placeholder="请选择状态"
            >
              <el-option
                v-for="item in statusList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="onSearch"
            >
              查询
            </el-button>
            <el-button
              v-has="['150101']"
              type="primary"
              @click="showDialog = true"
            >
              新增积分
            </el-button>
            <!-- TODO 加权限 -->
            <el-button
              type="primary"
              @click="showExportData = true"
            >
              导出
            </el-button>
          </el-form-item>
        </template>
      </SearchBar>
    </template>

    <LayoutTable
      ref="tokensManage"
      url="/extensions/currency/manage/currencyPager"
      :set-search="setSearch"
      disable-auto-height
      :param="tableForm"
    >
      <el-table-column
        prop="name"
        label="积分名称"
        min-width="120"
      />

      <el-table-column
        prop="logo"
        label="图标"
        min-width="100"
      >
        <template #default="scope">
          <el-image
            fit="fill"
            :src="scope.row.logo"
          />
        </template>
      </el-table-column>

      <el-table-column
        prop="todo"
        label="积分类型"
        min-width="100"
      >
        <template #default="{ row }">
          {{ row.isExternal ? '外部积分' : '内部积分' }}
        </template>
      </el-table-column>

      <el-table-column
        prop="exchangeRatio"
        label="兑换比例"
        min-width="120"
      />

      <el-table-column
        v-if="adminType == 0"
        prop="insNames"
        label="应用机构"
        min-width="200"
      >
        <template #default="scope">
          <div>
            {{ scope.row.insNames }}
          </div>
        </template>
      </el-table-column>

      <el-table-column
        prop="createTime"
        label="创建时间"
        min-width="160"
      >
        <template #default="scope">
          {{ dateFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="expireTime"
        label="失效时间"
        min-width="160"
      >
        <template #default="scope">
          {{ expireTimeFormat(scope.row) }}
        </template>
      </el-table-column>
      <!-- scope.row.expireTime ? dateFormat(scope.row.createTime): ''  -->
      <el-table-column
        v-has="['150102']"
        prop="status"
        label="积分状态"
        min-width="100"
      >
        <template #default="scope">
          <el-switch
            :value="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @click="setStatus(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column
        prop="updateTime"
        label="操作时间"
        min-width="160"
      >
        <template #default="scope">
          {{ dateFormat(scope.row.updateTime) }}
        </template>
      </el-table-column>

      <el-table-column
        v-has="['150103', '150104', '150105', '150106']"
        label="操作"
        width="150"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            v-has="['150103']"
            link
            type="primary"
            @click="toEdit(scope.row)"
          >
            编辑
          </el-button>

          <el-button
            v-has="['150104']"
            link
            type="primary"
            @click="$router.push(`/merchant/tokens/tokensManage/tokensDetail/${scope.row.id}?name=${scope.row.name}`)"
          >
            明细
          </el-button>

          <el-dropdown
            placement="bottom"
            @command="handleCommand($event, scope.row)"
          >
            <div style="margin-left: 10px; cursor: pointer">
              <el-button
                type="primary"
                link
              >
                更多
              </el-button>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-has="['150105']"
                  command="importTokens"
                >
                  积分导入
                </el-dropdown-item>
                <el-dropdown-item
                  v-has="['150106']"
                  command="exportTokens"
                >
                  积分导出
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button
            link
            type="primary"
            @click="openBatch(scope.row)"
          />
        </template>
      </el-table-column>
    </LayoutTable>
  </MainContent>
  <AddTokens
    :id="integralId"
    :show-dialog="showDialog"
    @confirm="confirm"
    @cancel="cancel"
  />
  <exportData
    v-model:show-dialog="showExportData"
    :search-data="tableForm"
    title="积分管理"
    export-type="currencyInfoExport"
  />
  <!-- 积分导入 -->
  <BatchImport
    :id="integralId"
    v-model:model-value="showBatch"
    @confirm="getResData"
  />
  <BatchImportRes
    v-model:show="showImportRes"
    v-model:loading="isLoading"
    :result="importRes"
    @close="closeImport"
  />
  <ExportTokens
    v-model:show="isShowExport"
    :row="currentRow"
  />
</template>
<script lang="ts">
export default {
  name: 'TokensManage'
}
</script>
<script lang="ts" setup>
import type { Ref } from "vue";
import type { ITokenItem } from "@/api/modules/tokensManagement";

import marketingCenterApi from "@/api/marketingCenterApi";
// import MedalAwarded from './component/MedalAwarded.vue'
// import ExportIntergal from "./component/ExportIntergal.vue";
import AddTokens from "./addTokens.vue";
import { dateFormat } from "@/utils/filters";
import exportData from "@/components/exportData/exportData.vue";
// import ScSelector from "@/components/scSelector/ScSelector.vue";
import BatchImport from "./batchImport.vue"
import BatchImportRes from "./batchImportRes.vue";
import ExportTokens from "./ExportTokens.vue";

const Store = useStore();
const showExportData = ref(false)
const tableForm = ref({
  name: "",
  status: null,
  queryInsIds: [],
  isExternal: false,
});
const dataForm = ref({
  day: 60 * 60 * 24,
});

const overTimeData = ref({
  dayEnd: "当天失效",
  weekEnd: "周末失效",
  monthEnd: "月末失效",
  yearEnd: "年末失效",
});
const statusList = ref([
  { id: null, name: "全部" },
  { id: 1, name: "启用" },
  { id: 0, name: "停用" },
]);
const adminType = ref(Store.state.user.adminType);
const integralId = ref();
const showDialog = ref(false);
// const modelId = ref(Number(null));
const setSearch = ref(Number());
const setStatus = (row: ITokenItem) => {
  ElMessageBox.confirm("是否修改状态?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      customerUpdateStatus(row);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};

const customerUpdateStatus = async (row: ITokenItem) => {
  let rs: any = await marketingCenterApi.updStatus({
    id: row.id,
    status: row.status == 0 ? 1 : 0,
    name: row.name
  });
  if (rs.code === 200) {
    ElMessage.success("状态修改成功");
    onSearch();
  }
};
const expireTimeFormat = (row: ITokenItem) => {
  if (row.expireType == "relatively") {
    return `${row.expireTime / dataForm.value.day}天`;
  } else if (row.expireType == "fixed") {
    return `${dateFormat(row.expireTime)}`;
  } else {
    return overTimeData.value[row.expireType]
  }
};
const toEdit = (row: ITokenItem) => {
  integralId.value = row.id;
  showDialog.value = true;
};
const confirm = () => {
  onSearch();
};

const cancel = () => {
  showDialog.value = false;

  setTimeout(() => {
    integralId.value = '';
  }, 500);
};

const onSearch = () => {
  setSearch.value++;
};

const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    onSearch();
  },
  {
    deep: true
  }
)

/****批量导入 */
const showBatch = ref(false)
const showImportRes = ref(false)
const isLoading = ref(false)
const openBatch = (row: ITokenItem) => {
  showBatch.value = true
  integralId.value = row.id;
}
//获取导入结果数据
const getResData = async (val: any) => {
  onSearch()
  if (val.key) {
    getImportResult(val.key)
    showImportRes.value = true
    isLoading.value = true
  }
}

//获取导入结果
let timer: Ref<ReturnType<typeof setTimeout> | undefined>  = ref()
const importRes = ref()
//记录请求次数
const timerCount = ref(0)
//轮询导入结果
const getImportResult = async (key: string) => {
  const rs = await marketingCenterApi.currencyImportRes({ key: key })
  if (rs.code == 200) {
    clearTimeout(timer.value)
    timer.value = undefined
    if (rs.payload && Object.keys(rs.payload).length) {
      timerCount.value = 0
      importRes.value = rs.payload
      isLoading.value = false

    } else {
      timerCount.value++
      clearTimeout(timer.value)
      timer.value = setTimeout(() => {
        if (timerCount.value > 150) {
          timerCount.value = 0
          isLoading.value = false
          clearTimeout(timer.value)
        } else {
          getImportResult(key)
        }
      }, 2000)
    }
  } else {
    isLoading.value = false
    timerCount.value = 0
    clearTimeout(timer.value)
    timer.value = null
  }
}

const closeImport = () => {
  timerCount.value = 0
  isLoading.value = false
  clearTimeout(timer.value)
  timer.value = null
}

const currentRow = ref();

const handleCommand = (command: string, row: any) => {
  switch (command) {
    case 'importTokens': 
      openBatch(row);
      break;
    case 'exportTokens':
      exportTokens(row);
      break;
    default:
      console.log("command not found: ", command);
  }
}

const isShowExport = ref(false);
const exportTokens = (row: any) => {
  isShowExport.value = true;
  currentRow.value = row;
}

//清除定时相关数据
onBeforeUnmount(() => {
  closeImport()
})

</script>

<style lang="scss" scoped>
:deep(.el-image) {
  border-radius: 3px;
  margin: 10px;
  width: 50px;
  height: 50px;
}
</style>
